package com.springboot.demo.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.cx.item.common.vo.ResultPageVo;
import com.springboot.demo.model.example.AreaExample;
import com.springboot.demo.model.model.Area;
import com.springboot.demo.service.AreaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by hwm on 2018/6/25.
 */
@Api(description = "地址")
@Controller
@RequestMapping("/area")
public class AreaController {

    @Autowired
    private AreaService areaService;

    /**
     * 根据城市编码获取下级
     *
     * @return
     */
    @ApiOperation("根据城市编码获取下级")
    @RequestMapping(value = "/getBelowAreaByAreaCode", method = RequestMethod.GET)
    @ResponseBody
    public ResultPageVo<List<Area>> getBelowAreaByAreaCode(String areaCode) {

        if (StrUtil.isEmpty(areaCode)) {
            return ResultPageVo.failure("areaCode为空", null);
        }

        AreaExample areaCodeExam = new AreaExample();
        AreaExample.Criteria areaCodeExamCriteria = areaCodeExam.createCriteria();
        areaCodeExamCriteria.andAreaCodeEqualTo(areaCode);
        List<Area> areas = areaService.selectByExample(areaCodeExam);
        if (CollUtil.isEmpty(areas)) {
            return ResultPageVo.failure("地址不存在", null);
        }

        Area area = areas.get(0);

        AreaExample areaExam = new AreaExample();
        AreaExample.Criteria areaExamCriteria = areaExam.createCriteria();
        if (area.getAreaLevel() == 1) {
            // 查询市
            areaExamCriteria.andAreaLevelEqualTo(2);
            areaExamCriteria.andProvinceCodeEqualTo(area.getAreaCode());
        } else if (area.getAreaLevel() == 2) {
            // 查询县/区域编码
            areaExamCriteria.andAreaLevelEqualTo(3);
            areaExamCriteria.andCityCodeEqualTo(area.getAreaCode());
        } else {
            return ResultPageVo.success(areas);
        }

        List<Area> areaList = areaService.selectByExample(areaExam);
        return ResultPageVo.success(areaList);
    }

    /**
     * 获取所有省份
     *
     * @return
     */
    @ApiOperation("获取所有省份")
    @RequestMapping(value = "/getAllProvince", method = RequestMethod.GET)
    @ResponseBody
    public ResultPageVo<List<Area>> getAllProvince() {

        AreaExample areaExam = new AreaExample();
        AreaExample.Criteria areaExamCriteria = areaExam.createCriteria();
        areaExamCriteria.andAreaLevelEqualTo(1);
        List<Area> areaList = areaService.selectByExample(areaExam);

        return ResultPageVo.success(areaList);
    }

}
